package fr.mairie.parc.page.materiel;

import javax.annotation.Resource;

import org.apache.click.control.Form;
import org.apache.click.control.ImageSubmit;
import org.apache.click.util.Bindable;
import org.springframework.context.ApplicationContext;

import fr.mairie.parc.context.AppContext;
import fr.mairie.parc.control.materiel.MaterielFields;
import fr.mairie.parc.domain.Materiel;
import fr.mairie.parc.page.BorderPage;
import fr.mairie.parc.service.MaterielManager;

public class ViewMaterielPage extends BorderPage {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	@Resource protected MaterielManager materielManager;
	@Bindable protected Form form = new Form();
	@Bindable protected Integer idMateriel;
	protected transient Materiel materiel;


	protected MaterielFields fields = new MaterielFields();

	public ViewMaterielPage() {
		fields.setReadonly(true);
		fields.addAll(form);
		form.add(new ImageSubmit("Cancel", "/assets/images/32x32/cancel.png",this, "onCancelClicked"));
	}

	@Override
	public void onInit() {
		super.onInit();
		ApplicationContext ctx = AppContext.getApplicationContext();
    	materielManager = (MaterielManager) ctx.getBean("materielManager");
	}

	@Override
	public void onRender() {
		if (idMateriel < 0) {
			msg = "Erreur, id invalide:" + idMateriel + " pour le materiel";
			setRedirect("error.htm");
			return;
		}
		if (materiel == null) {
			materiel =  materielManager.getMaterielById(idMateriel);
		}
		if (materiel == null) {
			msg = "Erreur, aucun materiel trouvé pour cet id :" + idMateriel;
			setRedirect("error.htm");
			return;
		}
		fields.setFieldsValues(materiel);
		super.onRender();
	}

	public boolean onCancelClicked() {
        setRedirect(MaterielPage.class);
        return false;
    }


}
